package com.msgqu.share.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @description:
 * @author: wsj
 * @create: 2020-11-12 15:13
 * @throws:
 */
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext appliactionContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appliactionContext = applicationContext;
    }
    /**
     * @description: 得到spring容器上下文
     * @author: wsj
     * @create: 2020-11-12 15:17
     * @throws
     */
    public static ApplicationContext getApplicationContext(){
        return appliactionContext;
    }
    /**
     * @description: 根据名称获取bean
     * @params: [name]
     * @author: wsj
     * @create: 2020-11-12 15:20
     */
    public static <T> T getBeanByBeanName(String name){
        return (T)getApplicationContext().getBean(name);
    }
    /**
     * @description: 根据类型获取Spring 中 bean 注意：这里不能有继承或者多实现关系，如果有请使用getBeanByBeanName
     * @params: [Class<T> t]
     * @author: wsj
     * @create: 2020-11-12 15:30
     */
    public static <T> T getBeanByType(Class<T> t){
        return getApplicationContext().getBean(t);
    }
    /**
     * @description: 根据接口或者抽象类获取实现或者继承的类的集合
     * @params: [Class<T> type]
     * @author: wsj
     * @create: 2020-11-12 15:43
     */
    public static <T> List<T> getBeanListOfType(Class<T> type){
        List<T> list = new ArrayList<>();
        Map<String, T> beansMap = getApplicationContext().getBeansOfType(type);
        Iterator<Map.Entry<String, T>> iterator = beansMap.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String, T> entry = iterator.next();
            list.add(entry.getValue());

        }
        return list;
    }

}
